﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Dapper;
using Entity;
using System.Data;
using IRealize;
using Realize;
using System.Threading.Tasks;

namespace WebApplication9.Controllers.DDGL
{
    public class DDDJController : Controller
    {
        private readonly IConfiguration configuration;

        public DDDJController(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult CX()
        {
            return View();
        }

        // 获取级联数据（I级→II级→III级）
        [HttpGet("FirstLevelCXDD")]
        public async Task<IActionResult> FirstLevelCXDD()
        {

            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

             

                // 1. 查询I级机构
                var firstKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT first_kind_id AS id, first_kind_name AS name 
              FROM config_file_first_kind 
              WHERE first_kind_id IS NOT NULL AND first_kind_name IS NOT NULL");

             
                // 2. 查询II级机构
                var secondKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT first_kind_id AS parentId, 
                     second_kind_id AS id, 
                     second_kind_name AS name 
              FROM config_file_second_kind 
              WHERE second_kind_id IS NOT NULL AND second_kind_name IS NOT NULL");


                // 3. 查询III级机构
                var thirdKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT second_kind_id AS parentId, 
                     third_kind_id AS id, 
                     third_kind_name AS name 
              FROM config_file_third_kind 
              WHERE third_kind_id IS NOT NULL AND third_kind_name IS NOT NULL");

                // 4. 构建级联数据（使用实体类）
                var result = new List<CascaderNode>();

                foreach (var first in firstKinds)
                {
                    var firstId = first.id;
                    var seconds = secondKinds.Where(s => s.parentId == firstId).ToList();

                    var secondList = new List<CascaderNode>(); // 明确为CascaderNode列表

                    foreach (var second in seconds)
                    {
                        var secondId = second.id;
                        // 构建III级节点（实体类）
                        var thirds = thirdKinds
                            .Where(t => t.parentId == secondId)
                            .Select(t => new CascaderNode
                            {  // 使用实体类
                                id = t.id,
                                name = t.name,
                                children = new List<CascaderNode>() // 子节点也是实体类列表
                            })
                            .ToList();

                        // 构建II级节点（实体类），此时thirds和空列表类型一致
                        secondList.Add(new CascaderNode
                        {
                            id = second.id,
                            name = second.name,
                            children = thirds.Any() ? thirds : new List<CascaderNode>() // 都是List<CascaderNode>
                        });
                    }

                    // 构建I级节点（实体类）
                    result.Add(new CascaderNode
                    {
                        id = first.id,
                        name = first.name,
                        children = secondList.Any() ? secondList : new List<CascaderNode>() // 类型一致
                    });
                }

                return Ok(result);
            }

        }


        public IActionResult Index2()
        {
            return View();
        }

       

        public async Task<IActionResult> DJLB(int pageSize, int currentPage)
        {

            string sqlserver = configuration["SqlServer"];
            using (SqlConnection conn = new SqlConnection(sqlserver))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@keyName", "huf_id");
                param.Add("@tableName", "human_file");
                param.Add("@currentPage", currentPage);
                param.Add("@totalRows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYedd] @pageSize, @keyName, @tableName, @currentPage, @totalRows out";
                List<Human_File> list = conn.Query<Human_File>(sql, param).ToList();

                FenYe<Human_File> fenYecs = new FenYe<Human_File>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("totalRows");
                //return fenYecs;
                return Json(fenYecs);

            }
        }


        public async Task<IActionResult> Search([FromBody] Human_File_Dig request)
        {

            IDDGLD dDGLD = new DDGLD();


            // 调用服务层执行查询
            var result = await dDGLD.CXHumanFiles(
               configuration["SqlServer"],
                request.first_kind_name,
                request.second_kind_name,
                request.third_kind_name,
                request.regist_time,
                request.check_time,
                request.PageNumber,
                request.PageSize

            );


            // 返回分页结果
            return Ok(new
            {
                TotalCount = result.TotalCount,
                Items = result.Items,
                PageNumber = result.PageNumber,
                PageSize = result.PageSize
            });


        }

        public IActionResult CXXS()
        {
            return View();
        }



        public IActionResult Update(int id)
        {

            return View();

        }

        public IActionResult Update2(int id)
        {
            return View();
        }


        // 获取级联数据（I级→II级→III级）
        [HttpGet("FirstLevelnewCX")]
        public async Task<IActionResult> FirstLevelnewCX()
        {

            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 查询所有I、II、III级机构的唯一数据
                var allOrgs = await connection.QueryAsync<dynamic>(
                    "SELECT DISTINCT " +
                    "first_kind_id AS id, first_kind_name AS name, 1 AS level " +
                    "FROM human_file_dig " +
                    "WHERE first_kind_id IS NOT NULL AND first_kind_name IS NOT NULL " +
                    "UNION ALL " +
                    "SELECT DISTINCT " +
                    "second_kind_id AS id, second_kind_name AS name, 2 AS level " +
                    "FROM human_file_dig " +
                    "WHERE second_kind_id IS NOT NULL AND second_kind_name IS NOT NULL " +
                    "UNION ALL " +
                    "SELECT DISTINCT " +
                    "third_kind_id AS id, third_kind_name AS name, 3 AS level " +
                    "FROM human_file_dig " +
                    "WHERE third_kind_id IS NOT NULL AND third_kind_name IS NOT NULL");

                // 构建级联数据结构
                var result = new List<dynamic>();

                // 筛选出I级机构(level=1)
                var firstLevelOrgs = allOrgs.Where(o => o.level == 1).DistinctBy(o => o.id).ToList();

                foreach (var firstLevelOrg in firstLevelOrgs)
                {
                    // 筛选出当前I级机构对应的II级机构(通过first_kind_id关联)
                    var secondLevelOrgs = allOrgs
                        .Where(o => o.level == 2 && o.id == firstLevelOrg.id) // II级机构ID与I级机构ID相同
                        .DistinctBy(o => o.id)
                        .ToList();

                    var secondList = new List<dynamic>();

                    foreach (var secondLevelOrg in secondLevelOrgs)
                    {
                        // 筛选出当前II级机构对应的III级机构(通过second_kind_id关联)
                        var thirdLevelOrgs = allOrgs
                            .Where(o => o.level == 3 && o.id == secondLevelOrg.id) // III级机构ID与II级机构ID相同
                            .DistinctBy(o => o.id)
                            .ToList();

                        secondList.Add(new
                        {
                            id = secondLevelOrg.id,
                            name = secondLevelOrg.name,
                            children = thirdLevelOrgs.Select(o => new { id = o.id, name = o.name }).ToList()
                        });
                    }

                    result.Add(new
                    {
                        id = firstLevelOrg.id,
                        name = firstLevelOrg.name,
                        children = secondList.Any() ? secondList : new List<dynamic>()
                    });
                }

                return Ok(result);
            }


        }


        [HttpGet("JobCategorynewCX")]
        public async Task<IActionResult> JobCategorynewCX()
        {
            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 1. 查询所有唯一的职位分类（第1级）
                var jobCategories = await connection.QueryAsync<dynamic>(
                    @"SELECT DISTINCT 
                human_major_kind_id AS id, 
                human_major_kind_name AS name 
              FROM human_file_dig 
              WHERE human_major_kind_id IS NOT NULL 
                AND human_major_kind_name IS NOT NULL");

                // 构建级联数据结构
                var result = new List<dynamic>();

                // 2. 遍历职位分类，查询对应的职位（第2级）
                foreach (var category in jobCategories)
                {
                    // 查询该职位分类下的所有职位
                    var jobs = await connection.QueryAsync<dynamic>(
                        @"SELECT DISTINCT 
                    human_major_id AS id, 
                    hunma_major_name AS name 
                  FROM human_file_dig 
                  WHERE human_major_kind_id = @CategoryId 
                    AND human_major_id IS NOT NULL 
                    AND hunma_major_name IS NOT NULL",
                        new { CategoryId = category.id });

                    // 确保children为非空数组
                    var jobList = jobs.ToList();

                    // 添加到结果集
                    result.Add(new
                    {
                        id = category.id,
                        name = category.name,
                        children = jobList.Any() ? jobList : new List<dynamic>() // 空数组处理
                    });
                }

                // 3. 返回级联数据
                return Ok(result);
            }



        }
        

      
        public async Task<IActionResult> DJCX(int id)
        {
            IRLXLK dDGLD = new RLXLK();
            Human_File fileDig = await dDGLD.SelectHFIDAsync(id, configuration["SqlServer"]);



            // 映射数据为前端需要的格式，包含原机构和原职位ID
            var result = new
            {
                success = true,
                data = new
                {

                    human_id = fileDig.human_id,
                    human_name = fileDig.human_name,
                    // 原机构信息
                    original_first_kind_id = fileDig.first_kind_id,
                    original_second_kind_id = fileDig.second_kind_id,
                    original_third_kind_id = fileDig.third_kind_id,
                    // 原职位信息
                    original_job_category_id = fileDig.human_major_kind_id,
                    major_kind_name = fileDig.human_major_kind_name,
                    major_name = fileDig.hunma_major_name,
                    original_job_id = fileDig.human_major_id,
                    // 原薪酬信息
                    salayid = fileDig.salary_standard_id,
                    original_salary_standard = fileDig.salary_standard_name,
                    original_salary_total = fileDig.salary_sum,


                    // 其他信息
                    registrant = fileDig.register,
                    transferReason = fileDig.remark,

                    id_card = fileDig.human_id_card,

                }
            };

            return Ok(result);
        }



        //新薪酬标准下拉框的绑定
        public async Task<IActionResult> XCBD()
        {
            IDDGLD dDGLD = new DDGLD();

          var salaryStandards = await dDGLD.XCXLK(configuration["SqlServer"]);

            // 将数据转换为下拉框需要的格式：[{value: id, label: name}]
            var options = new List<object>();
            foreach (var standard in salaryStandards)
            {
                options.Add(new { value = standard.salary_standard_id ,label = standard.salary_standard_name });
            }

            return Ok(options);

        }


        public async Task<IActionResult> AddDJ([FromBody] Major_Change model)
        {

            IDDGLD dDGLD = new DDGLD();


                // 调用AddHF方法
             int result = await dDGLD.AddMCTJ(model, configuration["SqlServer"]);

            if (result > 0)
            {
                return Ok(new { success = true, message = "添加成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "添加失败" });
            }


        }



    }
}
